import { reqChangePWD, reqLogout } from '@/api/users'
import { useRouter } from 'vue-router'
import { useUserStore } from '@/stores'
import { showModal, showMessage } from '@/utils/elementTools'
export const useRePassword = () => {
  // 修改密码
  const userStore = useUserStore()
  const router = useRouter()

  const formRef = useTemplateRef<HTMLInputElement>('formRef')
  const formDrawerRef = useTemplateRef<HTMLInputElement>('formDrawerRef')

  const form = reactive({
    oldpassword: '',
    password: '',
    repassword: ''
  })
  const rules = reactive({
    oldpassword: [
      { required: true, message: '请输入旧密码', trigger: 'blur' },
      { min: 4, max: 16, message: '长度在 4 到 16 个字符', trigger: 'blur' }
    ],
    password: [
      { required: true, message: '请输入新密码', trigger: 'blur' },
      { min: 4, max: 16, message: '长度在 4 到 16 个字符', trigger: 'blur' }
    ],
    repassword: [
      { required: true, message: '请输入确认密码', trigger: 'blur' },
      { min: 4, max: 16, message: '长度在 4 到 16 个字符', trigger: 'blur' }
    ]
  })
  const onSubmit = () => {
    ;(formRef.value as any).validate((valid: boolean) => {
      if (!valid) {
        return false
      }
      ;(formDrawerRef.value as any).showLoading()
      reqChangePWD(form)
        .then((res) => {
          if (res.msg == 'ok') {
            showMessage('密码修改成功，请重新登录！", "success")')
            // visibleDrawer.value = false
            ;(formDrawerRef.value as any).hideDrawer()
            userStore.clearUserInfo()
            router.push('/login')
          } else {
            console.log(res)
          }
        })
        .finally(() => {
          ;(formDrawerRef.value as any).hideLoading()
        })
    })
  }

  const openRePasswordForm = () => (formDrawerRef.value as any).showDrawer()

  return {
    form,
    rules,
    formRef,
    formDrawerRef,
    onSubmit,
    openRePasswordForm
  }
}

export function useLogout() {
  const userStore = useUserStore()
  const router = useRouter()
  const handleLogout = () => {
    showModal('是否真的要退出登录吗？')
      .then(async (res) => {
        const result = await reqLogout()
        if (result.msg == 'ok') {
          showMessage(result.data + '！')
        } else {
          console.log(result)
        }
        userStore.clearUserInfo()
        router.push('/login')
      })
      .catch((err) => {
        console.log(err)
      })
  }
  return {
    handleLogout
  }
}
